//
//  ParleysObject.m
//  ipadclient
//
//  Created by Stéphane Prohaszka on 26/05/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "ParleysService.h"

#import "JSON.h"
#import "Presentation.h"
#import "Space.h"
#import "Channel.h"

//static NSString* const kURLPresentations = @"http://www.parleys.com/parleysserver/rest/mobile/presentations.form?id=74957&index=0&paging=20";
static NSString* const kURLSpaces = @"http://server.parleys.com/rest/v2/spaces.form";
static NSString* const kURLChannels = @"http://server.parleys.com/rest/v2/spaces/%i/channels.form";
static NSString* const kURLPresentations = @"http://server.parleys.com/rest/v2/spaces/%i/channels/%i/presentations.form";
//static NSString* const kURLPresentations = @"http://server.parleys.com/rest/v2/spaces/189/channels/102906/presentations.form";
static NSString* const kPresentationsFile = @"presentations";

static ParleysService* sharedInstance = nil;

@implementation ParleysService

@synthesize channels;
@synthesize spaces;
@synthesize presentations;

- (id) init {
    self = [super init];
    if (self) {
        jsonData = nil;
        
        channels = [[NSMutableArray alloc] init];
        spaces = [[NSMutableArray alloc] init];
        presentations = [[NSMutableArray alloc] init];
        
        spacesConnection = nil;
        channelsConnection = nil;
        presentationsConnection = nil;
        
        activeSpaceId = 0;
    }
    return self;
}

- (void) dealloc {
    if (jsonData != nil) {
        [jsonData release];
    }
    
    if (spacesConnection != nil) {
        [spacesConnection release];
    }
    if (channelsConnection != nil) {
        [channelsConnection release];
    }
    if (presentationsConnection != nil) {
        [presentationsConnection release];
    }
    
    [self dealloc];
}

#pragma mark -
#pragma mark NSURLConnection
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    if (jsonData != nil) {
        [jsonData release];
    }
    jsonData = [[NSMutableData alloc] init];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    [jsonData appendData:data];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
    if (connection == spacesConnection) {
        [self parseSpacesJSON];
    } else if (connection == channelsConnection) {
        [self parseChannelsJSON];
    } else if (connection == presentationsConnection) {
        [self parsePresentationsJSON];
    } else {
        NSLog(@"Unknown Connection !");
    }
}

#pragma mark -
#pragma mark Custom
+ (ParleysService*) sharedService {
    if (sharedInstance == nil) {
        sharedInstance = [[ParleysService alloc] init];
    }
    return sharedInstance;
}

- (void) loadSpaces {
    NSURL* url = [[NSURL alloc] initWithString:kURLSpaces];
    NSURLRequest* request = [[NSURLRequest alloc] initWithURL:url];
    spacesConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
    [spacesConnection release];
    [request release];
    [url release];
}

- (void) loadChannelsFromSpace:(Space*)space {
    [self loadChannelsFromSpaceId:space.identification];
}

- (void) loadChannelsFromSpaceId:(int)spaceId {
    // For Channel creation purpose
    activeSpaceId = spaceId;
    
    NSURL* url = [[NSURL alloc] initWithString:[NSString stringWithFormat:kURLChannels, spaceId]];
    NSURLRequest* request = [[NSURLRequest alloc] initWithURL:url];
    channelsConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
    [request release];
    [url release];
}

- (void) loadPresentationsFromChannel:(Channel*)channel {
    [self loadPresentationsFromChannel:channel.identification andSpace:channel.spaceId];
}

- (void) loadPresentationsFromChannel:(int)channelId andSpace:(int)spaceId {
    NSURL* url = [[NSURL alloc] initWithString:[NSString stringWithFormat:kURLPresentations, spaceId, channelId]];
    NSLog(@"Presentations url trying to load: %@", [url description]);
    NSURLRequest* request = [[NSURLRequest alloc] initWithURL:url];
    presentationsConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
    [request release];
    [url release];
}

- (NSString*) presentationsFile {
    NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
                                                         NSUserDomainMask,
                                                         YES);
    NSString* documentDirectory = [paths objectAtIndex:0];
    NSString* file = [documentDirectory stringByAppendingFormat:kPresentationsFile];
    return file;
}

- (void) parseSpacesJSON {
    SBJsonParser* jsonParser = [[SBJsonParser alloc] init];
    id jsonObjects = [jsonParser objectWithData:jsonData];
    
    for (NSDictionary* jsonObject in jsonObjects) {
        Space* space = [[Space alloc] initWithJson:jsonObject];
        [spaces addObject:space];
        [space release];
    }
    //[spaces writeToFile:@"" atomically:YES];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"SpacesLoaded"
                                                        object:nil];
}

- (void) parseChannelsJSON {
    SBJsonParser* jsonParser = [[SBJsonParser alloc] init];
    id jsonObjects = [jsonParser objectWithData:jsonData];
    
    NSLog(@"Channels to load: %@", [jsonObjects description]);
    
    // Clean the list from previous values
    [channels removeAllObjects];
    
    for (NSDictionary* jsonObject in jsonObjects) {
        Channel* channel = [[Channel alloc] initWithJson:jsonObject];
        channel.spaceId = activeSpaceId;
        [channels addObject:channel];
        [channel release];
    }
    
    NSLog(@"ChannelsLoaded");
    [[NSNotificationCenter defaultCenter] postNotificationName:@"ChannelsLoaded"
                                                        object:nil];
}

- (void) parsePresentationsJSON {
    SBJsonParser* jsonParser = [[SBJsonParser alloc] init];
    id jsonObjects = [jsonParser objectWithData:jsonData];
    
    NSLog(@"Presentations to load: %@", [jsonObjects description]);
    
    // Clean the list from previous values
    [presentations removeAllObjects];
    
    for (NSDictionary* jsonObject in jsonObjects) {
        Presentation* presentation = [[Presentation alloc] initWithJson:jsonObject];
        [presentations addObject:presentation];
        NSLog(@"Presentation: %@", presentation.title);
        [presentation release];
    }
    
    NSLog(@"PresentationsLoaded");
    [[NSNotificationCenter defaultCenter] postNotificationName:@"PresentationsLoaded"
                                                        object:nil];
}

@end
